﻿/*
 * 2014-11-15
 *  1.需要支持多个附件的发送(已经支持)
 *  2.可以通过HTML标签来发送更多不同格式的邮件
 */

using System.Net;
using System.Net.Mail;
using System.Text;

namespace Ycg.Utility
{
    public class MailHelper
    {      
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="from">发送人地址</param>
        /// <param name="displayName">发送人显示的名称</param>
        /// <param name="to">收件人地址</param>
        /// <param name="subject">标题</param>
        /// <param name="body">正文</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="serverAddress">服务器地址</param>
        /// <param name="timeout">发送邮件超时时间(默认10秒)</param>
        /// <param name="port">邮箱服务器的端口(默认25)</param>
        /// <param name="attachmemtPath">邮件附件(支持添加多个附件)</param>
        public static void SendMail(string from, string displayName, string to, string subject, string body,
                                    string userName, string password, string serverAddress, int timeout = 10000, int port = 25, params string[] attachmemtPath)
        {
            MailMessage mailMessage = new MailMessage
            {
                Body = body,
                Subject = subject,
                IsBodyHtml = true,
                BodyEncoding = Encoding.Default,
                From = new MailAddress(from, displayName)
            };

            mailMessage.To.Add(new MailAddress(to));

            if (attachmemtPath != null && attachmemtPath.Length > 0)
            {
                foreach (string path in attachmemtPath)
                {
                    mailMessage.Attachments.Add(new Attachment(path));
                }
            }

            SmtpClient smtpClient = new SmtpClient(serverAddress, port) //邮箱服务器以及端口
            {
                Timeout = timeout,
                UseDefaultCredentials = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential(userName, password) //添加邮箱帐户(用户名)和密码
            };

            smtpClient.Send(mailMessage);
        }
    }
}